﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Platform.Storage.Redis
{
	public static class RedisUtility
	{
		//private static readonly Regex redisEncoder = new Regex( @"[\?\*\:\\\r\n]", RegexOptions.Compiled | RegexOptions.IgnoreCase );
		private static readonly Regex redisEncoder = new Regex( @"[\r\n]", RegexOptions.Compiled | RegexOptions.IgnoreCase );
		private const string EncoderReplacement = "\\$&";

		public static RedisReplyStatus GetReply( string line )
		{
			if ( String.IsNullOrEmpty( line ) )
				return RedisReplyStatus.None;
			else
				return ( RedisReplyStatus )line[ 0 ];
		}

		public static string[] InsertFirst( this string[] vector, params string[] value )
		{
			if ( vector == null || vector.Length == 0 )
			{
				if ( value == null )
					return new string[] { };
				else
					return value;
			}
			else
			{
				int len = vector.Length;
				var result = new string[ len + value.Length ];

				Array.Copy( value, 0, result, 0, value.Length );
				Array.Copy( vector, 0, result, value.Length, len );

				return result;
			}
		}

		public static string[] InsertFirst(this IEnumerable<string> vector, IEnumerable<string> values)
		{
			return vector.ToArray().InsertFirst( values.ToArray() );
		}

		internal static IEnumerable<string> AsString(this IEnumerable<IndexItem> indexes)
		{
			return indexes.SelectMany( i => i.AsString() );
		}

		internal static IEnumerable<string> AsString(this IndexItem index)
		{
			yield return Convert.ToString( index.Score );
			yield return index.Field;
		}

		public static string Encode( string word )
		{
			return redisEncoder.Replace( word, "\n\n" );
		}

		internal static StringBuilder AppendEncoded( this StringBuilder msg, string content )
		{
		//	string tmp = Convert.ToBase64String( Encoding.Default.GetBytes( content ) );
			msg.Append( redisEncoder.Replace( content, "\n\n" ) );
			return msg;
		}
	}
}
